import { defineStore } from 'pinia'
import axios from '@/http'
import router from '@/router'

type UserInfo = {
  usrName: string
}
type UserStateProps = {
  token: string,
  userInfo: UserInfo | null,
  roles: Array<string>
}
export const useUserStore = defineStore('user', {
  state: ():UserStateProps => {
    return {
      token: '',
      // 用户信息
      userInfo: null,
      // 用户角色
      roles: []
    }
  },
  actions: {
    setToken (token:string) {
      this.token = token
    },
    // 登录
    login (params: any) {
      return new Promise((resolve, reject) => {
        axios.post('/user/login', params).then((res) => {
          // 储存token
          this.setToken(res.data.data.token)
          resolve(res)
        }).catch((err) => reject(err))
      })
    },
    // 获取用户信息
    getUserInfo () {
      return new Promise((resolve, reject) => {
        axios.get('/user/getInfo').then((res) => {
          // 保存 用户信息
          this.userInfo = res.data.data.userInfo
          // 保存 角色信息
          this.roles = res.data.data.roles || []

          resolve(res.data.data)
        }).catch((err) => reject(err))
      })
    },

    // 处理登出逻辑
    loginout () {
      // 清除权限信息
      this.token = ''
      this.roles = []
      this.userInfo = null
      sessionStorage.removeItem('user')
      sessionStorage.removeItem('permissions')
      router.push('/login')
    }
  },
  persist: {
    paths: ['token', 'userInfo', 'roles'],
    storage: sessionStorage
  }
})
export default useUserStore
